package top.lishuoboy.ssm.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.lishuoboy.dependency.base.db.MyDbUtil;
import top.lishuoboy.ssm.bean.People;
import top.lishuoboy.ssm.bean.User;
import top.lishuoboy.ssm.mapper.UserMapper;

import javax.sql.DataSource;
import java.util.Map;

@Slf4j
@Controller
public class SsmController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DataSource ds;
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/helloSpringMVC")
    @ResponseBody
    private String helloSpringMVC() {
        log.warn("helloSpringMVC");
        return "helloSpringMVC";
    }

    @Autowired
    private People people;

    @GetMapping("/helloSpring")
    @ResponseBody
    private String helloSpring() {
        log.warn("helloSpring, people=={}", people);
        return "helloSpring";
    }

    @GetMapping("/helloJdbcTemplate")
    @ResponseBody
    private String helloJdbcTemplate() {
        Map<String, Object> user = jdbcTemplate.queryForMap("select * from INFORMATION_SCHEMA.users");
        log.warn("user=={}", user);   // user=={NAME=ROOT, ADMIN=true, REMARKS=, ID=2}
        return "helloJdbcTemplate, user==" + user;
    }

    /** 参考 mybatis-spring 官网：http://mybatis.org/spring/zh/index.html */
    @GetMapping("/helloMybatis")
    @ResponseBody
    private String helloMybatis() {
        resetDbData();
        User user = userMapper.selectById(1);
        log.warn("helloSpring, user=={}", user);    // user==User(id=1, name=张三, psw=111)
        return "helloSpring, user==" + user;
    }

    /** 重置数据库 */
    private void resetDbData() {
        MyDbUtil.resetData(ds, "db_sql/lishuoboy-ssm.sql");
    }
}